package com.travel.server.manager.impl.command.order;

import com.travel.common.util.CommonUtil;
import com.travel.server.manager.dto.request.order.UpdateOrderPriceRequest;
import com.travel.server.manager.dto.response.EmptyResponse;
import com.travel.server.manager.impl.command.AbstractCommand;
import com.travel.server.manager.impl.dal.OrderDal;
import com.travel.server.manager.model.OrderInfo;
import com.travel.server.manager.model.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/5 18:18
 * @Desc:
 */
@Component
@Slf4j
public class UpdateOrderPriceCommand extends AbstractCommand<UpdateOrderPriceRequest, EmptyResponse> {

    @Autowired
    private OrderDal orderDal;

    @Override
    protected void checkInput(UpdateOrderPriceRequest request) {
        if (request.getId() == null){
            throwInvalidParam();
        }
    }

    @Override
    public EmptyResponse handle(UpdateOrderPriceRequest request) {
        checkInput(request);
        UserInfo userInfo = getUserInfo();
        Date now = new Date();

        OrderInfo orderInfo = orderDal.selectById(request.getId());
        if(request.getUpdateAmount() != null){
            int discountAmount = CommonUtil.yuanToFen(request.getUpdateAmount()).intValue();
            if(orderInfo.getDiscountAmount() != null){
                discountAmount = discountAmount + orderInfo.getDiscountAmount();
            }
            orderInfo.setDiscountAmount(discountAmount);
        }
        if(request.getFreightAmount() != null){
            orderInfo.setFreightAmount(CommonUtil.yuanToFen(request.getFreightAmount()).intValue());
        }

        orderInfo.setUpdateBy(userInfo.getName());
        orderInfo.setUpdateTime(now);
        orderDal.insertOrUpdate(orderInfo);

        return new EmptyResponse();
    }
}
